package org.leetcode.middle.leetcode216;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Solution {

    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();

    int sum = 0;

    public List<List<Integer>> combinationSum3(int k, int n) {

        backtracking(n, k, 1);
        return result;
    }


    private void backtracking2(int n, int k, int index, int sum) {
        if (path.size() == k) {
            if (sum==n){
                result.add(new ArrayList<>(path));
            }
            return;
        }

        for (int i = index; i <= 9; i++) {
            sum += i;
            path.add(i);
            backtracking2(n, k, i + 1, sum);
            sum -= i;
            path.remove(path.size() - 1);
        }
    }

    private void backtracking(int n, int k, int startIndex) {
        if (path.size() == k) {
            if (sum == n) result.add(new ArrayList<>(path));

            return;
        }

        for (int i = startIndex; i <= 9; i++) {
            sum = sum + i;
            path.add(i);
            backtracking(n, k, i + 1);
            //sum也要回溯
            sum = sum - i;
            path.removeLast();
        }
    }

    //剪枝
    private void backtrackingPro(int n, int k, int startIndex) {
        if (sum > n) {
            return;
        }

        if (path.size() == k) {
            if (sum == n) result.add(new ArrayList<>(path));

            return;
        }

        for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {
            sum = sum + i;
            path.add(i);
            backtracking(n, k, i + 1);
            //sum也要回溯
            sum = sum - i;
            path.removeLast();
        }
    }
}
